import {
    createRouter,
    createWebHashHistory,
    createWebHistory
} from "vue-router";
import Home from '../components/Home.vue'
import storage from "@/utils/storage";
import utils from "@/utils/utils";
import API from "@/api"

const modules = import.meta.glob('../views/*.vue')

const routes = [
    {
        name: 'home',
        path: '/welcome',
        meta: {
            title: '首页'
        },
        component: Home,
        redirect: '/welcome',
        children: [
            {
                name: 'welcome',
                path: '/welcome',
                meta: {
                    title: '欢迎页'
                },
                component: () => import('../views/Welcome.vue'),
            },
            // {
            //     name: 'user',
            //     path: '/system/user',
            //     meta: {
            //         title: '用户管理'
            //     },
            //     component: () => import('../views/User.vue'),
            // },
            // {
            //     name: 'menu',
            //     path: '/system/menu',
            //     meta: {
            //         title: '菜单管理'
            //     },
            //     component: () => import('../views/Menu.vue'),
            // },
            // {
            //     name: 'role',
            //     path: '/system/role',
            //     meta: {
            //         title: '角色管理'
            //     },
            //     component: () => import('../views/Role.vue'),
            // },
            // {
            //     name: 'dept',
            //     path: '/system/dept',
            //     meta: {
            //         title: '部门管理'
            //     },
            //     component: () => import('../views/Dept.vue'),
            // },
        ]
    },
    {
        name: 'default',
        path: '/',
        redirect: '/login',
    },
    {
        name: 'login',
        path: '/login',
        meta: {
            title: '登录页'
        },
        component: () => import('../views/Login.vue'),
    },
    {
        name: '404',
        path: '/404',
        meta: {
            title: '页面不存在'
        },
        component: () => import('../views/404.vue'),
    }
]

const router = createRouter({
    history: createWebHashHistory(),
    routes
})

// console.log(modules)

export async function loadAsyncRoutes() {
    console.log('loadAsyncRoutes')
    let userInfo = storage.getItem('userInfo') || {}
    if (userInfo.token) {
        try {
            const {menuList} = await API.getPermissionList();
            let $routes = utils.generateRoute(menuList);
            $routes.map((route) => {
                route.component = modules[`../views/${route.component}.vue`];
                router.addRoute("home", route);
            })
        } catch (error) {
            console.log(error)
        }
    }
}

// （已解决）登录页时会执行，但是这时候没有登录就没有token，就添加不了路由，登录后又没有再次执行这个方法，所以路由记录没有添加，刚登录进去所以页面跳转404
await loadAsyncRoutes();

// 判断当前地址是否可以访问
// function checkPermission(path) {
//     let hasPermission = router.getRoutes().filter(route => route.path == path).length;
//     if (hasPermission) {
//         return true;
//     } else {
//         return false;
//     }
// }

// 导航守卫
router.beforeEach((to, from, next) => {

    // if (checkPermission(to.path)) {
    if (router.hasRoute(to.name)) {
        document.title = to.meta.title;
        // 从登录进来前获取路由
        if (from.path === '/login') {
            loadAsyncRoutes();
        }
        next();
    } else {
        next('/404')
    }
})
export default router
